#include "core.h"

#include <QUdpSocket>

Core::Core(QObject *parent) : QObject(parent),
    m_pUdpSocket(new QUdpSocket(this))
{
    qDebug()<<"bind--"<<m_pUdpSocket->bind(QHostAddress::AnyIPv4, 3333,QAbstractSocket::ReuseAddressHint);
    qDebug()<<"join--"<<m_pUdpSocket->joinMulticastGroup(QHostAddress("225.1.0.0"));

    connect(m_pUdpSocket,SIGNAL(readyRead()),
            this,SLOT(slotMulticastRead()));
}

void Core::getAllDevInfo()
{
    reply_struct s;
    s.device_function=Function_Any;
    s.device_type=Type_Any;

    qDebug()<<"write--"<<m_pUdpSocket->writeDatagram((char *)(&s),sizeof(s),
                                                     QHostAddress::Broadcast,3333);
}

void Core::slotMulticastRead()
{
    while (m_pUdpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(m_pUdpSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        m_pUdpSocket->readDatagram(datagram.data(), datagram.size(),
                                   &sender, &senderPort);

        reply_struct reSt;

        char *data=datagram.data();
        memcpy((void*)&reSt,(void*)data,sizeof(data));
        //set the host addr

        if(reSt.device_type==Type_Host)
            m_hostReplyList.append(reSt);
        else if(reSt.device_type==Type_Client)
            m_clientReplyList.append(reSt);

        qDebug()<<"replay--"<<reSt.device_type<<reSt.device_name<<sender.toString();
    }
}
